﻿using UnityEngine;
using System.Collections;

public class EnemyDetectionScript : MonoBehaviour {

	float detectRange = 10f;
	float detectAngle = 55f;

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		checkForEnemy ();
	}

	bool checkForEnemy(){
		Collider[] collide = Physics.OverlapSphere (new Vector3 (transform.position.x, transform.position.y, transform.position.z), detectRange, 1 << LayerMask.NameToLayer ("Player"));
		if (collide.Length > 0) {
			if(checkVisionAngle(collide[0].attachedRigidbody.transform.position)){
				if(checkObstacles(collide[0].attachedRigidbody.transform.position)){
					//gun.Shoot();
				}
			}
		}
		return false;
	}
	
	bool checkObstacles(Vector3 position){
		RaycastHit hit;
		Vector3 direction = new Vector3 (position.x - transform.position.x, position.y - transform.position.y, position.z - transform.position.z);
		Ray ray = new Ray (direction, transform.position);
		if (Physics.Raycast (ray, out hit, Vector3.Distance (transform.position, position), 1 << LayerMask.NameToLayer ("Background"))) {
			//Debug.DrawRay (transform.position, direction, Color.blue, 1);
		}
		if (hit.point.x == 0 && hit.point.y == 0) {
			return true;
		} else {
			return false;
		}
	}
	
	bool checkVisionAngle(Vector3 position){
		Vector3 targetDir = position - transform.position;
		float angle = Vector3.Angle(targetDir, transform.forward);
		if (angle <= detectAngle) {
			return true;
		} else {
			return false;
		}
	}
}
